<?php
    require_once './Tool/DB/SqlDBManager.class.php';

    $sqlDBManager = new SqlDBManager();

    $NRIC = $_REQUEST['barcode'];

    if(!empty($_SESSION['selectedBackDate'])){
        $date=$_SESSION['selectedBackDate'];
    }else{
        $date=date('Y-m-d', time());
    }
    
    $Username = $_SESSION['username'];
    $centreId="";

    $sql = "Select * from attendancerecord where NRIC=? AND DATE(SignInTimeStamp) like ?";
    $parameters = array($NRIC,$date.'%');
    $res=$sqlDBManager->queryRows($sql,$parameters);

    if (empty($res)) {
        $signInTimeStamp = $date . ' 00:00:00';
        $signOutTimeStamp = $date . ' 00:00:00';
    	$sql = "SELECT client.CentreId FROM  client WHERE NRIC = ?";
    	$parameters = array($NRIC);
    	$res=$sqlDBManager->queryRow($sql,$parameters);
    	if(!empty($res)){
            $centreId = $res[0];
        }else{
            $centreId = 0;
        }
        $sql = "INSERT INTO attendancerecord (NRIC, CentreId, SignInTimeStamp, SignOutTimeStamp, Status, AuditSignIn) VALUES (?,?,?,?,?,?)";
        $parameters=array($NRIC,$centreId,$signInTimeStamp,$signOutTimeStamp,'BackDated',$Username);
        $res = $sqlDBManager->execute_dml($sql,$parameters);

        if ($res>0) {
            echo "<font color='red'>Back Date Success!</font>";
        } else {
            echo "<font color='red'>Back Date NOT Successful!</font>";
        }
    } else {
        echo "<font color='red'>Attendance for that elderly has been taken already!</font>";
    }
?>	